package com.bsdsma.fengheguaiapp.restcontroller;

import com.bsdsma.fengheguaiapp.constants.ErrorCodes;
import com.bsdsma.fengheguaiapp.dto.DataGroupByDateDto;
import com.bsdsma.fengheguaiapp.dto.UserAddDto;
import com.bsdsma.fengheguaiapp.dto.UserQueryDto;
import com.bsdsma.fengheguaiapp.entity.User;
import com.bsdsma.fengheguaiapp.enums.Role;
import com.bsdsma.fengheguaiapp.exceptionhandler.GlobalRuntimeException;
import com.bsdsma.fengheguaiapp.service.UserService;
import com.bsdsma.fengheguaiapp.utils.DateUtils;
import com.bsdsma.fengheguaiapp.utils.ResultUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/api/users")
public class UserRestController {

    @Autowired
    private UserService userService;

    @GetMapping
    public Map<String, Object> query(UserQueryDto dto){
        return ResultUtils.ok(userService.query(dto));
    }

    @GetMapping(value = "/partners")
    public Map<String, Object> listPartners(){
        List<User> users = userService.listByRole(Role.PARTNER);
        return ResultUtils.ok(users);
    }

    @GetMapping(value = "/{id}")
    public Map<String, Object> getById(@PathVariable Long id){
        User user = userService.getById(id);
        if(null == user){
            throw new GlobalRuntimeException(ErrorCodes.OBJ_ALREADY_EXISTS, "查无此用户");
        }
        return ResultUtils.ok(user);
    }

    @PostMapping
    public Map<String, Object> add(@RequestBody UserAddDto dto){
        userService.add(dto);
        return ResultUtils.ok();
    }

    @PostMapping("/{id}")
    public Map<String, Object> update(@PathVariable Long id, @RequestBody UserAddDto dto){
        userService.update(id, dto);
        return ResultUtils.ok();
    }

    @DeleteMapping(value = "/{id}")
    public Map<String, Object> delete(@PathVariable Long id){
        userService.delete(id);
        return ResultUtils.ok();
    }

    @GetMapping(value = "/count")
    public Map<String, Object> count(){
        Long count = userService.count();
        return ResultUtils.ok(null == count ? 0L : count);
    }

    /**
     * 日新增统计
     */
    @GetMapping(value = "/day-newly-added")
    public Map<String, Object> dayNewlyAdded(){
        // 今天
        Date endDate = DateUtils.getNow();
        // 30天以前
        Date beginDate = DateUtils.dayAfter(endDate, -30);
        List<DataGroupByDateDto> dataList = userService.countByDay(beginDate, endDate);
        return ResultUtils.ok(dataList);
    }
}
